package com.woniuxy.order.client;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Flowable 服务客户端
 * 通过 HTTP 调用 flowable-server 的 API
 */
@Slf4j
@Component
public class FlowableClient {
    
    // 使用网关地址，通过网关访问flowable服务
    private String flowableServiceUrl = "http://localhost:9999/flowable-server";
    
    /**
     * 启动订单审批流程
     * 
     * @param processKey 流程定义Key
     * @param businessKey 业务键（订单ID）
     * @param variables 流程变量
     * @return 流程实例ID
     */
    public String startProcess(String processKey, String businessKey, Map<String, Object> variables) {
        try {
            String url = flowableServiceUrl + "/workflow/process/start";
            
            Map<String, Object> params = new HashMap<>();
            params.put("processDefinitionKey", processKey);
            params.put("businessKey", businessKey);
            params.put("variables", variables);
            
            log.info("启动流程，URL: {}, 参数: {}", url, JSONUtil.toJsonStr(params));
            
            String response = HttpUtil.createPost(url)
                    .header("Content-Type", "application/json")
                    .body(JSONUtil.toJsonStr(params))
                    .execute()
                    .body();
            Map<String, Object> result = JSONUtil.toBean(response, Map.class);
            
            // 检查响应是否成功
            Boolean success = (Boolean) result.get("success");
            if (success != null && success) {
                // 从 data 字段中获取 processInstanceId
                Map<String, Object> data = (Map<String, Object>) result.get("data");
                if (data != null && data.containsKey("processInstanceId")) {
                    String processInstanceId = (String) data.get("processInstanceId");
                    log.info("流程启动成功，流程实例ID: {}", processInstanceId);
                    return processInstanceId;
                } else {
                    throw new RuntimeException("响应中缺少 processInstanceId");
                }
            } else {
                String message = (String) result.get("message");
                throw new RuntimeException("启动流程失败: " + (message != null ? message : "未知错误"));
            }
            
        } catch (Exception e) {
            log.error("调用 Flowable 服务失败", e);
            throw new RuntimeException("启动流程失败: " + e.getMessage());
        }
    }
    
    /**
     * 完成任务
     * 
     * @param taskId 任务ID
     * @param variables 流程变量
     */
    public void completeTask(String taskId, Map<String, Object> variables) {
        try {
            String url = flowableServiceUrl + "/workflow/completeFlow";
            
            Map<String, Object> params = new HashMap<>();
            params.put("taskId", taskId);
            params.put("variables", variables);
            
            log.info("完成任务，URL: {}, 参数: {}", url, JSONUtil.toJsonStr(params));
            
            String response = HttpUtil.createPost(url)
                    .header("Content-Type", "application/json")
                    .body(JSONUtil.toJsonStr(params))
                    .execute()
                    .body();
            log.info("任务完成成功，响应: {}", response);
            
        } catch (Exception e) {
            log.error("完成任务失败", e);
            throw new RuntimeException("完成任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 自动完成第一个任务（办事处商务填写订单）
     * 
     * @param username 用户名
     * @param processInstanceId 流程实例ID
     */
    public void completeFirstTask(String username, String processInstanceId) {
        try {
            // 1. 查询用户的待办任务
            String queryUrl = flowableServiceUrl + "/workflow/queryUserFlow?userName=" + username;
            String queryResponse = HttpUtil.createPost(queryUrl)
                    .header("Content-Type", "application/json")
                    .execute()
                    .body();
            
            Map<String, Object> queryResult = JSONUtil.toBean(queryResponse, Map.class);
            Boolean success = (Boolean) queryResult.get("success");
            
            if (success != null && success) {
                List<Map<String, Object>> tasks = (List<Map<String, Object>>) queryResult.get("data");
                if (tasks != null && !tasks.isEmpty()) {
                    // 找到对应流程实例的第一个任务
                    for (Map<String, Object> task : tasks) {
                        String taskProcessInstanceId = (String) task.get("processInstanceId");
                        if (processInstanceId.equals(taskProcessInstanceId)) {
                            String taskId = (String) task.get("taskId");
                            
                            // 2. 自动完成该任务（通过）
                            String completeUrl = flowableServiceUrl + "/workflow/acceptFlow?taskId=" + taskId;
                            String completeResponse = HttpUtil.createPost(completeUrl)
                                    .header("Content-Type", "application/json")
                                    .execute()
                                    .body();
                            
                            log.info("自动完成第一个任务成功，taskId: {}, response: {}", taskId, completeResponse);
                            return;
                        }
                    }
                }
            }
            
            log.warn("未找到需要自动完成的任务，username: {}, processInstanceId: {}", username, processInstanceId);
            
        } catch (Exception e) {
            log.error("自动完成第一个任务失败", e);
            // 不抛出异常，避免影响主流程
        }
    }
    
    /**
     * 查询待办任务
     * 
     * @param assignee 处理人
     * @return 任务列表
     */
    public String getTasksByAssignee(String assignee) {
        try {
            String url = flowableServiceUrl + "/workflow/queryUserFlow?userName=" + assignee;
            
            log.info("查询待办任务，URL: {}", url);
            
            String response = HttpUtil.get(url);
            log.info("查询待办任务成功，响应: {}", response);
            
            return response;
            
        } catch (Exception e) {
            log.error("查询待办任务失败", e);
            throw new RuntimeException("查询待办任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询流程状态
     * 
     * @param processInstanceId 流程实例ID
     * @return 流程状态信息
     */
    public String getProcessStatus(String processInstanceId) {
        try {
            String url = flowableServiceUrl + "/workflow/process/status?processInstanceId=" + processInstanceId;
            
            log.info("查询流程状态，URL: {}", url);
            
            String response = HttpUtil.get(url);
            log.info("查询流程状态成功，响应: {}", response);
            
            return response;
            
        } catch (Exception e) {
            log.error("查询流程状态失败", e);
            throw new RuntimeException("查询流程状态失败: " + e.getMessage());
        }
    }
}



